package com.bds.btcdc.web.action;

import java.nio.charset.Charset;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bds.btcdc.web.model.TUser;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.web.model.common.UserSession;
import com.bds.btcdc.web.service.UserService;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.CookieUtils;
import com.bds.btcdc.web.utils.DESUtil;
import com.bds.btcdc.web.utils.RedisUtil;

/**
 * Created by DongChenchen on 2018/4/18 0018
 */
@Controller
public class LoginAction extends  BaseAction{
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(Map<String, Object> map, HttpServletRequest request) {

        return "redirect:/ftl/login/login.html";
    }

    /**
     * 登录提交
     * @param request
     * @return
     */
    @RequestMapping(value = "/action/login/submit")
    @ResponseBody
    public String loginSubmitForm(HttpServletRequest request, HttpServletResponse response) {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String rememberme=request.getParameter("rememberme");
        Result ret =new Result();
        try {
            ret = userService.login(username,password,request, response);
            if (ret.getCode()==Const.SUC) {

                TUser u = (TUser) ret.getData();
                UserSession userSession = new UserSession(u);
                //将登录信息存入redis,并设置key的失效时间（setex与set同时y 会覆盖value值）
                String userstr = Base64.encodeBase64String(SerializationUtils.serialize(userSession));
                //RedisUtil.getInstance().hash().hset(Const.REDIS_SESSION_HASH_KEY,email,userstr);
                RedisUtil.getInstance().strings().setEx(String.valueOf(u.getId()),Const.REMEMBERME_TIME,userstr);
                if("on".equals(rememberme)) {
                    //将email加密后存入cookie（客户端）
                    Charset CHARSET = Charset.forName("utf-8");
                    String encryptResult = DESUtil.encrypt(String.valueOf(u.getId()), CHARSET, Const.DESKEY);
                    CookieUtils.addCookie(response,Const.COOKIES_USER_KEY,encryptResult,Const.REMEMBERME_TIME, request.getServerName());
                }else{
                    //客户端默认存一天
                    Charset CHARSET = Charset.forName("utf-8");
                    String encryptResult = DESUtil.encrypt(String.valueOf(u.getId()), CHARSET, Const.DESKEY);
                    CookieUtils.addCookie(response,Const.COOKIES_USER_KEY,encryptResult,60*60*24, request.getServerName());
                }
            }
        } catch (Exception e) {
            log.error("用户登录异常", e);
            ret.setResult(Const.FAIL, "用户登录异常");
        }
       return "success_jsonpCallback"+"("+this.parseJson(ret)+")";
    }
    @RequestMapping(value = "/ftl/login/submit2",method = RequestMethod.POST)
    @ResponseBody
    public Result loginSubmit(HttpServletRequest request, HttpServletResponse response) {
        Result ret =null;
        try {
            ret = userService.login(request, response);
            if (ret.getCode()==Const.SUC) {
                String email=request.getParameter("email");
                String rememberme=request.getParameter("rememberme");
                TUser u = (TUser) ret.getData();
                UserSession userSession = new UserSession(u);
                //将登录信息存入redis,并设置key的失效时间（setex与set同时y 会覆盖value值）
                String userstr = Base64.encodeBase64String(SerializationUtils.serialize(userSession));
//                RedisUtil.getInstance().hash().hset(Const.REDIS_SESSION_HASH_KEY,email,userstr);
                RedisUtil.getInstance().strings().setEx(email,Const.REMEMBERME_TIME,userstr);
                if("on".equals(rememberme)) {
                    //将email加密后存入cookie（客户端）
                    Charset CHARSET = Charset.forName("utf-8");
                    String encryptResult = DESUtil.encrypt(email + "", CHARSET, Const.DESKEY);
                    CookieUtils.addCookie(response,Const.COOKIES_USER_KEY,encryptResult,Const.REMEMBERME_TIME, Const.DOMAIN);
                }else{
                    //客户端默认存一天
                    Charset CHARSET = Charset.forName("utf-8");
                    String encryptResult = DESUtil.encrypt(email + "", CHARSET, Const.DESKEY);
                    CookieUtils.addCookie(response,Const.COOKIES_USER_KEY,encryptResult,60*60*24, Const.DOMAIN);
                }
            }
        } catch (Exception e) {
            log.error("用户登录异常", e);
            ret=new Result();
            ret.setResult(Const.FAIL, "用户登录异常");
        }
        return ret;
    }
}
